home *** CD-ROM | disk | FTP | other *** search
/ Personal Computer World 2008 February / PCWFEB08.iso / Software / Freeware / Miro 1.0 / Miro_Installer.exe / xulrunner / python / platformutils.py < prev    next >
Encoding:
Python Source  |  2007-11-12  |  7.6 KB  |  230 lines

  1. # Miro - an RSS based video player application
  2. # Copyright (C) 2005-2007 Participatory Culture Foundation
  3. #
  4. # This program is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License as published by
  6. # the Free Software Foundation; either version 2 of the License, or
  7. # (at your option) any later version.
  8. #
  9. # This program is distributed in the hope that it will be useful,
  10. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12. # GNU General Public License for more details.
  13. #
  14. # You should have received a copy of the GNU General Public License
  15. # along with this program; if not, write to the Free Software
  16. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301 USA
  17.  
  18. ###############################################################################
  19. #### Helper method used to get the free space on the disk where downloaded ####
  20. #### movies are stored                                                     ####
  21. ###############################################################################
  22.  
  23. import ctypes
  24. import _winreg
  25. import config
  26. import prefs
  27. import os
  28. import logging
  29. import resources
  30. import sys
  31. import urllib
  32. from util import (returnsUnicode, returnsBinary, checkU, checkB, call_command,
  33.         AutoflushingStream)
  34.  
  35. localeInitialized = False
  36. FilenameType = unicode
  37.  
  38. def samefile(path1, path2):
  39.     return getLongPathName(path1) == getLongPathName(path2)
  40.  
  41. def getLongPathName(path):
  42.     buf = ctypes.create_unicode_buffer(260) 
  43.     GetLongPathName = ctypes.windll.kernel32.GetLongPathNameW
  44.     rv = GetLongPathName(path, buf, 260)
  45.     if rv == 0 or rv > 260:
  46.         return path
  47.     else:
  48.         return buf.value
  49.  
  50. def getAvailableBytesForMovies():
  51.     # TODO: windows implementation
  52.     moviesDir = config.get(prefs.MOVIES_DIRECTORY)
  53.     freeSpace = ctypes.c_ulonglong(0)
  54.     availableSpace = ctypes.c_ulonglong(0)
  55.     totalSpace = ctypes.c_ulonglong(0)
  56.     rv = ctypes.windll.kernel32.GetDiskFreeSpaceExW(unicode(moviesDir),
  57.             ctypes.byref(availableSpace), ctypes.byref(totalSpace),
  58.             ctypes.byref(freeSpace)) 
  59.     if rv == 0:
  60.         print "GetDiskFreeSpaceExW failed, returning bogus value!"
  61.         return 100 * 1024 * 1024 * 1024
  62.     return availableSpace.value
  63.  
  64. #############################################################################
  65. # Windows specific locale                                                   #
  66. #############################################################################
  67. _langs = {
  68. 0x401: "ar",
  69. 0x416: "pt_BR",
  70. 0x804: "zh_CN", # Chinese simplified
  71. 0x404: "zh_TW", # Chinese traditional
  72. 0x405: "cs",
  73. 0x406: "da",
  74. 0x413: "nl",
  75. #0x409: "en",  # This is the default. Don't bother with gettext in that case
  76. 0x40b: "fi",
  77. 0x40c: "fr",
  78. 0x407: "de",
  79. 0x408: "el",
  80. 0x40d: "he",
  81. 0x40e: "hu",
  82. 0x410: "it",
  83. 0x411: "jp",
  84. 0x412: "ko",
  85. 0x414: "nb",
  86. 0x415: "pl",
  87. 0x816: "pt",
  88. 0x419: "ru",
  89. 0xc0a: "es",
  90. 0x41D: "sv",
  91. 0x41f: "tr",
  92. }
  93.  
  94. def _getLocale():
  95.     code = ctypes.windll.kernel32.GetUserDefaultUILanguage()
  96.     try:
  97.         return _langs[code]
  98.     except:  # Hmmmmm, we don't know the language for this code
  99.         return None
  100.  
  101. def initializeLocale():
  102.     global localeInitialized
  103.     lang = _getLocale()
  104.     if lang:
  105.         os.environ["LANGUAGE"] = lang
  106.     localeInitialized = True
  107.  
  108. _loggingSetup = False
  109. def setupLogging (inDownloader=False):
  110.     global _loggingSetup
  111.     if _loggingSetup:
  112.         return
  113.  
  114.     if not inDownloader:
  115.         logFile = config.get(prefs.LOG_PATHNAME)
  116.         logStream = open(logFile, "wt")
  117.         sys.stdout = sys.stderr = AutoflushingStream(logStream)
  118.     else:
  119.         # If we're in the dwnloader sys.stdout and sys.stderr have already
  120.         # been redirected
  121.         logStream = sys.stderr
  122.     logging.basicConfig(level=logging.DEBUG,
  123.                         format='%(asctime)s %(levelname)-8s %(message)s',
  124.                         stream=logStream)
  125.     _loggingSetup = True
  126.  
  127. # Takes in a unicode string representation of a filename and creates a
  128. # valid byte representation of it attempting to preserve extensions
  129. #
  130. # This is not guaranteed to give the same results every time it is run,
  131. # not is it garanteed to reverse the results of filenameToUnicode
  132. @returnsUnicode
  133. def unicodeToFilename(filename, path = None):
  134.     @returnsUnicode
  135.     def shortenFilename(filename):
  136.         checkU(filename)
  137.         # Find the first part and the last part
  138.         pieces = filename.split(u".")
  139.         lastpart = pieces[-1]
  140.         if len(pieces) > 1:
  141.             firstpart = u".".join(pieces[:-1])
  142.         else:
  143.             firstpart = u""
  144.         # If there's a first part, use that, otherwise shorten what we have
  145.         if len(firstpart) > 0:
  146.             return u"%s.%s" % (firstpart[:-1],lastpart)
  147.         else:
  148.             return filename[:-1]
  149.  
  150.     checkU(filename)
  151.     if path:
  152.         checkU(path)
  153.     else:
  154.         path = os.getcwd()
  155.  
  156.     # Keep this a little shorter than the max length, so we can run
  157.     # nextFilename
  158.     MAX_LEN = 200
  159.     
  160.     filename.replace('/','_').replace("\000","_").replace("\\","_").replace(":","_").replace("*","_").replace("?","_").replace("\"","_").replace("<","_").replace(">","_").replace("|","_")
  161.  
  162.     newFilename = filename
  163.     while len(newFilename) > MAX_LEN:
  164.         newFilename = shortenFilename(newFilename)
  165.  
  166.     return newFilename
  167.  
  168. # Given a filename in raw bytes, return the unicode representation
  169. #
  170. # Since this is not guaranteed to give the same results every time it is run,
  171. # not is it garanteed to reverse the results of unicodeToFilename
  172. @returnsUnicode
  173. def filenameToUnicode(filename, path = None):
  174.     if path:
  175.         checkU(path)
  176.     checkU(filename)
  177.     return filename
  178.  
  179. # Takes filename given by the OS and turn it into a FilenameType
  180. def osFilenameToFilenameType(filename):
  181.     return FilenameType(filename)
  182.  
  183. # Takes an array of filenames given by the OS and turn them into a FilenameTypes
  184. def osFilenamesToFilenameTypes(filenames):
  185.     return [osFilenameToFilenameType(filename) for filename in filenames]
  186.  
  187. # Takes a FilenameType and turn it into something the OS accepts.
  188. def filenameTypeToOSFilename(filename):
  189.     return filename
  190.  
  191. # Takes in a byte string or a unicode string and does the right thing
  192. # to make a URL
  193. @returnsUnicode
  194. def makeURLSafe(string, safe = '/'):
  195.     checkU(string)
  196.     return urllib.quote(string.encode('utf_8'), safe=safe).decode('ascii')
  197.  
  198. # Undoes makeURLSafe
  199. @returnsUnicode
  200. def unmakeURLSafe(string):
  201.     checkU(string)
  202.     return urllib.unquote(string.encode('ascii')).decode('utf_8')
  203.  
  204. def resizeImage(source_path, dest_path, width, height):
  205.     """Resize an image to a smaller size.
  206.     
  207.     Guidelines:
  208.  
  209.     Don't try to expand up the image.
  210.  
  211.     Don't change the aspect ratio
  212.  
  213.     The final image should be have the exact dimensions <width>X<height>.  If
  214.     there is extra room, either because the source image was smaller
  215.     specified, or because it had a different aspect ratio, pad out the image
  216.     with black pixels.
  217.     """
  218.     convert_path = os.path.join(resources.appRoot(), '..', 'imagemagick',
  219.             'convert.exe')
  220.     # From the "Pad Out Image" recipe at
  221.     # http://www.imagemagick.org/Usage/thumbnails/
  222.     border_width = max(width, height) / 2
  223.     call_command(convert_path,  source_path, 
  224.             "-strip",
  225.             "-resize", "%dx%d>" % (width, height), 
  226.             "-gravity", "center", "-bordercolor", "black",
  227.             "-border", "%s" % border_width,
  228.             "-crop", "%dx%d+0+0" % (width, height),
  229.             "+repage", dest_path)
  230.